import pygame
import logging
from datetime import datetime, timedelta
from typing import Optional, Dict, List
from ..theme import Theme
from ..game import TypingGame
from ..speech_manager import SpeechManager
import os
from ..word_bank import WordBank
from ..user_profile import UserProfile

class StudyView:
    def __init__(self, screen: pygame.Surface, theme: Theme, word_bank: WordBank, user_profile: UserProfile):
        self.screen = screen
        self.theme = theme
        self.word_bank = word_bank
        self.user_profile = user_profile
        
        # 视图状态
        self.state = "check_plan"  # check_plan, create_plan, confirm_plan, study, review
        
        # 学习计划相关
        self.active_plan = None
        self.today_words = []
        self.review_words = []
        self.current_word_index = 0
        self.current_input = ""
        self.show_word_info = False
        
        # 界面元素
        self.width = screen.get_width()
        self.height = screen.get_height()
        self.buttons = {}
        self.refresh_buttons()
        
        # 加载当前学习计划
        self.load_active_plan()
        
        # 初始化游戏和语音管理器
        self.game = TypingGame()
        self.speech = SpeechManager()
        
        # 设置为学习模式
        self.game.set_mode("study")
        
        # 加载用户选择的词库
        self.load_selected_wordbank()
        
        # 学习状态
        self.input_text = ""
        self.result = None
        self.show_result = False
        self.study_started = False
        
        # 加载音效（添加错误处理）
        try:
            # 确保音频系统已初始化
            if not pygame.mixer.get_init():
                pygame.mixer.init()
            
            # 尝试加载音效
            sound_dir = os.path.join("assets", "sounds")
            if not os.path.exists(sound_dir):
                os.makedirs(sound_dir)  # 创建音效目录
                
            correct_sound_path = os.path.join(sound_dir, "correct.wav")
            wrong_sound_path = os.path.join(sound_dir, "wrong.wav")
            
            # 如果音效文件不存在，使用默认值
            self.correct_sound = (pygame.mixer.Sound(correct_sound_path) 
                                if os.path.exists(correct_sound_path) 
                                else None)
            self.wrong_sound = (pygame.mixer.Sound(wrong_sound_path)
                              if os.path.exists(wrong_sound_path)
                              else None)
        except Exception as e:
            logging.warning(f"加载音效失败: {str(e)}")
            self.correct_sound = None
            self.wrong_sound = None
        
    def refresh_buttons(self) -> None:
        """刷新按钮"""
        if self.state == "check_plan":
            # 创建新计划按钮
            self.buttons["create_plan"] = pygame.Rect(
                self.width/2 - 100,
                self.height/2 + 50,
                200, 40
            )
            # 恢复计划按钮（如果有）
            if self.active_plan:
                self.buttons["resume_plan"] = pygame.Rect(
                    self.width/2 - 100,
                    self.height/2 - 50,
                    200, 40
                )
        elif self.state == "create_plan":
            # 创建计划的按钮
            self.buttons["confirm"] = pygame.Rect(
                self.width/2 - 100,
                self.height - 100,
                200, 40
            )
    
    def load_selected_wordbank(self):
        """加载用户选择的词库"""
        try:
            # 尝试读取用户选择的词库
            wordbank_file = os.path.join("data", "user_data", "selected_wordbank.txt")
            if os.path.exists(wordbank_file):
                with open(wordbank_file, 'r') as f:
                    selected_wordbank = f.read().strip()
            else:
                selected_wordbank = "cet4"  # 默认使用四级词库
                
            # 加载词库
            if not self.game.load_wordbank(selected_wordbank):
                print(f"加载词库 {selected_wordbank} 失败，使用默认词库")
                self.game.load_wordbank("cet4")
        except Exception as e:
            print(f"加载词库失败: {str(e)}")
            self.game.load_wordbank("cet4")
            
    def load_active_plan(self) -> None:
        """加载当前活动的学习计划"""
        self.active_plan = self.user_profile.get_active_plan()
        if self.active_plan:
            self.load_study_words()
    
    def load_study_words(self) -> None:
        """加载今天需要学习的单词"""
        if not self.active_plan:
            return
            
        # 获取今天的新单词
        words_per_day = self.active_plan["words_per_day"]
        bank_name = self.active_plan["word_bank"]
        
        # 确保使用正确的词库
        if self.word_bank.current_bank != bank_name:
            self.word_bank.load_word_bank(bank_name)
        
        # 获取新的学习单词
        self.today_words = self.word_bank.get_words(words_per_day)
        
        # TODO: 获取需要复习的单词
        self.review_words = []
    
    def handle_event(self, event: pygame.event.Event) -> Optional[str]:
        """处理事件"""
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                return "menu"
        
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_pos = pygame.mouse.get_pos()
            
            if self.state == "check_plan":
                # 检查是否点击了创建新计划按钮
                if self.buttons["create_plan"].collidepoint(mouse_pos):
                    self.state = "create_plan"
                    self.refresh_buttons()
                    return None
                
                # 检查是否点击了恢复计划按钮
                if "resume_plan" in self.buttons and self.buttons["resume_plan"].collidepoint(mouse_pos):
                    self.state = "study"
                    self.load_study_words()
                    return None
            
            elif self.state == "create_plan":
                # 检查是否点击下拉框
                if "dropdown" in self.buttons and self.buttons["dropdown"].collidepoint(mouse_pos):
                    self.dropdown_expanded = not getattr(self, 'dropdown_expanded', False)
                    return None
                
                # 如果下拉框展开，检查选项点击
                if getattr(self, 'dropdown_expanded', False):
                    for bank_name, button in self.buttons.items():
                        if bank_name.startswith("bank_") and button.collidepoint(mouse_pos):
                            selected_bank = bank_name[5:]  # 移除 "bank_" 前缀
                            self.word_bank.set_word_bank(selected_bank)
                            self.dropdown_expanded = False
                            return None
                
                # 检查推荐计划按钮
                recommendations = self.user_profile.get_plan_recommendations(len(self.word_bank.words))
                for i in range(len(recommendations)):
                    if self.buttons[f"select_plan_{i}"].collidepoint(mouse_pos):
                        plan = recommendations[i]
                        self._create_plan_from_template(plan)
                        return None
                
                # 检查自定义计划按钮
                if self.buttons["custom_plan"].collidepoint(mouse_pos):
                    self._show_create_plan_dialog()
                    return None
        
        elif self.state == "custom_plan":
            if event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                
                # 检查输入框点击
                for key in ['name', 'words_per_day', 'duration_days']:
                    if self.buttons[f"input_{key}"].collidepoint(mouse_pos):
                        self.custom_plan_params['active_field'] = key
                        return None
                
                # 检查确认按钮
                if self.buttons["custom_confirm"].collidepoint(mouse_pos):
                    # 创建自定义计划
                    plan = {
                        "name": self.custom_plan_params["name"],
                        "words_per_day": self.custom_plan_params["words_per_day"],
                        "target_date": (datetime.now() + 
                                      timedelta(days=self.custom_plan_params["duration_days"])).strftime("%Y-%m-%d")
                    }
                    self._create_plan_from_template(plan)
                    self.state = "study"
                    return None
                
                # 检查取消按钮
                if self.buttons["custom_cancel"].collidepoint(mouse_pos):
                    self.state = "create_plan"
                    return None
            
            elif event.type == pygame.KEYDOWN:
                active_field = self.custom_plan_params['active_field']
                if active_field:
                    if event.key == pygame.K_RETURN:
                        self.custom_plan_params['active_field'] = None
                    elif event.key == pygame.K_BACKSPACE:
                        value = str(self.custom_plan_params[active_field])
                        self.custom_plan_params[active_field] = value[:-1] or (0 if active_field != 'name' else '')
                    else:
                        value = str(self.custom_plan_params[active_field])
                        if active_field == 'name':
                            if event.unicode.isprintable():
                                self.custom_plan_params[active_field] = value + event.unicode
                        else:  # 数字字段
                            if event.unicode.isdigit():
                                new_value = int(value + event.unicode)
                                if new_value > 0:
                                    self.custom_plan_params[active_field] = new_value
        
        elif self.state == "study":
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    return "menu"
                elif event.key == pygame.K_SPACE:
                    # 切换显示单词信息
                    self.show_word_info = not self.show_word_info
                elif event.key == pygame.K_TAB:
                    # 朗读单词
                    if self.today_words:
                        word = self.today_words[self.current_word_index]["word"]
                        self.speech.speak(word)
                elif event.key == pygame.K_RETURN:
                    # 检查答案
                    if self.today_words and self.current_input:
                        word = self.today_words[self.current_word_index]["word"]
                        self.result = self.current_input.lower() == word.lower()
                        self.show_result = True
                        
                        # 如果正确，准备下一个单词
                        if self.result:
                            # 记录学习进度
                            self.user_profile.update_word_progress(
                                self.today_words[self.current_word_index]["word"],
                                self.result
                            )
                            self.current_word_index += 1
                            if self.current_word_index >= len(self.today_words):
                                self.current_word_index = 0
                                self.today_words = []  # 清空单词列表，表示完成
                        
                        self.current_input = ""
                        if self.correct_sound:
                            self.correct_sound.play()
                elif event.key == pygame.K_BACKSPACE:
                    self.current_input = self.current_input[:-1]
                    self.show_result = False
                else:
                    # 只接受字母输入
                    if event.unicode.isalpha():
                        self.current_input += event.unicode
                        self.show_result = False
            
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
                mouse_pos = pygame.mouse.get_pos()
                
                # 如果学习任务完成，检查返回按钮点击
                if not self.today_words and "back_to_menu" in self.buttons:
                    if self.buttons["back_to_menu"].collidepoint(mouse_pos):
                        return "menu"
                
                # 如果显示结果，点击任意位置继续
                if self.show_result:
                    self.show_result = False
                    return None
        
        return None
    
    def draw(self) -> None:
        """绘制界面"""
        self.screen.fill(self.theme.background_color)
        
        if self.state == "check_plan":
            self._draw_check_plan()
        elif self.state == "create_plan":
            self._draw_create_plan()
        elif self.state == "custom_plan":
            self._draw_create_plan()  # 绘制背景
            self._draw_custom_plan_dialog()  # 绘制对话框
        elif self.state == "study":
            self._draw_study_interface()
        elif self.state == "review":
            self._draw_review_interface()
    
    def _draw_check_plan(self) -> None:
        """绘制检查计划界面"""
        # 绘制标题卡片
        title_card_rect = pygame.Rect(self.width/2 - 250, 50, 500, 80)
        self.theme.draw_card(self.screen, title_card_rect, with_shadow=True)
        
        # 绘制标题
        self.theme.draw_text(
            self.screen, 
            "学习计划", 
            (self.width/2, 90), 
            center=True, 
            size=36, 
            color=self.theme.primary_color,
            shadow=True
        )
        
        # 创建内容卡片
        content_card_rect = pygame.Rect(self.width/2 - 350, 170, 700, 350)
        self.theme.draw_card(self.screen, content_card_rect, with_shadow=True)
        
        if self.active_plan:
            # 绘制活动计划信息
            plan_title = f"当前计划: {self.active_plan['name']}"
            self.theme.draw_text(
                self.screen, 
                plan_title, 
                (self.width/2, 210), 
                center=True, 
                size=28,
                color=self.theme.primary_color
            )
            
            # 绘制计划信息
            info_x = self.width/2 - 300
            info_items = [
                f"词库: {self.active_plan['word_bank']}",
                f"每日单词数: {self.active_plan['words_per_day']}",
                f"目标日期: {self.active_plan['target_date']}",
                f"总单词数: {self.active_plan['total_words']}",
                f"已学习: {self.active_plan['progress']['learned_words']}",
                f"记忆良好: {self.active_plan['progress']['mastered_words']}"
            ]
            
            for i, info in enumerate(info_items):
                y = 250 + i * 35
                self.theme.draw_text(
                    self.screen, 
                    info, 
                    (info_x, y), 
                    center=False, 
                    size=20,
                    color=self.theme.text_color
                )
            
            # 绘制进度条
            progress = self.active_plan['progress']['learned_words'] / self.active_plan['total_words']
            progress_text = f"总体进度: {int(progress * 100)}%"
            
            progress_rect = pygame.Rect(self.width/2 - 250, 460, 500, 25)
            self.theme.draw_progress_bar(
                self.screen, 
                progress_rect, 
                progress, 
                progress_text
            )
            
            # 绘制"继续学习"按钮
            resume_button = pygame.Rect(self.width/2 - 120, 500, 240, 50)
            self.buttons["resume_plan"] = resume_button
            
            # 检测鼠标悬停
            mouse_pos = pygame.mouse.get_pos()
            is_hover = resume_button.collidepoint(mouse_pos)
            
            self.theme.draw_button(
                self.screen, 
                resume_button, 
                "继续学习", 
                is_hover=is_hover
            )
            
        else:
            # 如果没有活动计划，显示提示信息
            self.theme.draw_text(
                self.screen, 
                "你还没有学习计划", 
                (self.width/2, 250), 
                center=True, 
                size=28,
                color=self.theme.text_color
            )
            
            self.theme.draw_text(
                self.screen, 
                "创建一个新的学习计划来开始背单词吧！", 
                (self.width/2, 300), 
                center=True, 
                size=22,
                color=self.theme.text_color
            )
            
            # 添加一些鼓励性的文字
            message = "坚持每天学习，你会惊讶于自己的进步！"
            self.theme.draw_text(
                self.screen, 
                message, 
                (self.width/2, 350), 
                center=True, 
                size=18,
                color=self.theme.accent_color
            )
            
            # 显示小贴士
            tips = [
                "小贴士: 每天学习20个单词，坚持45天就能记住900个单词！",
                "小贴士: 艾宾浩斯记忆法可以帮助你更有效地记忆单词！",
                "小贴士: 提前记忆单词，考试时你将更加从容！"
            ]
            
            tip = tips[int(pygame.time.get_ticks() / 5000) % len(tips)]
            tip_rect = pygame.Rect(self.width/2 - 300, 400, 600, 60)
            self.theme.draw_rounded_rect(
                self.screen, 
                tip_rect, 
                (*self.theme.primary_color[:3], 50),  # 半透明背景
                border=0
            )
            
            self.theme.draw_text(
                self.screen, 
                tip, 
                (self.width/2, 430), 
                center=True, 
                size=16,
                color=self.theme.primary_color
            )
        
        # 绘制"创建新计划"按钮
        create_button = pygame.Rect(self.width/2 - 120, self.height - 100, 240, 50)
        self.buttons["create_plan"] = create_button
        
        # 检测鼠标悬停
        mouse_pos = pygame.mouse.get_pos()
        is_hover = create_button.collidepoint(mouse_pos)
        
        # 使用强调色
        self.theme.draw_button(
            self.screen, 
            create_button, 
            "创建新计划", 
            is_hover=is_hover,
            is_active=True  # 使用强调色
        )
    
    def _draw_create_plan(self) -> None:
        """绘制创建计划界面"""
        # 绘制标题卡片
        title_card_rect = pygame.Rect(self.width/2 - 250, 30, 500, 80)
        self.theme.draw_card(self.screen, title_card_rect, with_shadow=True)
        
        # 绘制标题
        self.theme.draw_text(
            self.screen, 
            "创建学习计划", 
            (self.width/2, 70), 
            center=True, 
            size=36, 
            color=self.theme.primary_color,
            shadow=True
        )
        
        # 绘制词库选择器卡片
        wordbank_card_rect = pygame.Rect(50, 130, self.width - 100, 120)
        self.theme.draw_card(self.screen, wordbank_card_rect, with_shadow=True)
        
        # 绘制词库选择标题
        self.theme.draw_text(
            self.screen, 
            "选择词库", 
            (self.width/2, 155), 
            center=True, 
            size=24,
            color=self.theme.primary_color
        )
        
        # 创建词库选择下拉框
        dropdown_width = 300
        dropdown_rect = pygame.Rect(
            self.width/2 - dropdown_width/2, 
            180, 
            dropdown_width, 
            40
        )
        
        # 检测鼠标悬停
        mouse_pos = pygame.mouse.get_pos()
        is_dropdown_hover = dropdown_rect.collidepoint(mouse_pos)
        border_color = self.theme.primary_color if is_dropdown_hover else self.theme.border_color
        
        # 绘制下拉框
        self.theme.draw_rounded_rect(
            self.screen, 
            dropdown_rect, 
            self.theme.card_bg_color, 
            border=2, 
            border_color=border_color
        )
        
        # 绘制下拉框文本
        self.theme.draw_text(
            self.screen, 
            self.word_bank.current_bank, 
            (dropdown_rect.left + 20, dropdown_rect.centery), 
            center=False, 
            size=20,
            color=self.theme.text_color
        )
        
        # 绘制下拉图标
        arrow_down = "▼"
        self.theme.draw_text(
            self.screen, 
            arrow_down, 
            (dropdown_rect.right - 20, dropdown_rect.centery), 
            center=True, 
            size=16,
            color=self.theme.primary_color
        )
        
        self.buttons["dropdown"] = dropdown_rect
        
        # 如果下拉框展开，显示选项
        if getattr(self, 'dropdown_expanded', False):
            # 获取可用词库列表
            available_banks = self.word_bank.list_word_banks()
            
            # 绘制下拉选项背景
            options_height = len(available_banks) * 40
            options_rect = pygame.Rect(
                dropdown_rect.left, 
                dropdown_rect.bottom, 
                dropdown_rect.width, 
                options_height
            )
            
            self.theme.draw_rounded_rect(
                self.screen, 
                options_rect, 
                self.theme.card_bg_color, 
                border=2, 
                border_color=self.theme.border_color
            )
            
            # 绘制选项
            for i, bank in enumerate(available_banks):
                option_rect = pygame.Rect(
                    dropdown_rect.left, 
                    dropdown_rect.bottom + i * 40, 
                    dropdown_rect.width, 
                    40
                )
                
                # 检测鼠标悬停
                is_option_hover = option_rect.collidepoint(mouse_pos)
                
                # 绘制选项背景
                if is_option_hover:
                    self.theme.draw_rounded_rect(
                        self.screen, 
                        option_rect, 
                        (*self.theme.primary_color[:3], 50),  # 半透明高亮
                        border=0
                    )
                
                # 绘制选项文本
                self.theme.draw_text(
                    self.screen, 
                    bank, 
                    (option_rect.left + 20, option_rect.centery), 
                    center=False, 
                    size=18,
                    color=self.theme.text_color
                )
                
                # 保存按钮引用
                self.buttons[f"bank_{bank}"] = option_rect
        
        # 绘制分隔线
        pygame.draw.line(
            self.screen, 
            self.theme.border_color,
            (50, 270),
            (self.width - 50, 270),
            2
        )
        
        # 绘制当前计划列表
        self.theme.draw_text(
            self.screen,
            "当前学习计划",
            (self.width/2, 300),
            center=True,
            size=24,
            color=self.theme.primary_color
        )
        
        # 获取用户的所有计划
        user_plans = self.user_profile.get_all_plans()
        max_plans = self.user_profile.get_max_plans()
        
        # 绘制计划列表卡片
        plans_card_rect = pygame.Rect(50, 330, self.width - 100, 120)
        self.theme.draw_card(self.screen, plans_card_rect, with_shadow=True)
        
        if user_plans:
            # 每行显示2个计划
            for i, plan in enumerate(user_plans):
                # 计算位置
                col = i % 2
                row = i // 2
                
                x = plans_card_rect.left + 30 + col * ((plans_card_rect.width - 60) / 2)
                y = plans_card_rect.top + 25 + row * 50
                
                # 创建计划信息卡片
                plan_rect = pygame.Rect(x, y, 400, 40)
                
                # 绘制计划信息背景
                self.theme.draw_rounded_rect(
                    self.screen, 
                    plan_rect, 
                    (*self.theme.card_bg_color[:3], 200),
                    border=1,
                    border_color=self.theme.border_color
                )
                
                # 绘制计划信息
                plan_info = (
                    f"{plan['name']} | {plan['word_bank']} | "
                    f"每日{plan['words_per_day']}词 | "
                    f"进度: {plan['progress']['learned_words']}/{plan['total_words']}"
                )
                
                self.theme.draw_text(
                    self.screen,
                    plan_info,
                    (plan_rect.left + 10, plan_rect.centery),
                    center=False,
                    size=16,
                    color=self.theme.text_color
                )
        else:
            # 如果没有计划，显示提示信息
            self.theme.draw_text(
                self.screen,
                "暂无学习计划",
                (plans_card_rect.centerx, plans_card_rect.centery),
                center=True,
                size=20,
                color=(160, 160, 160)
            )
        
        # 显示计划数量限制
        limit_text = f"计划数量: {len(user_plans)}/{max_plans}"
        self.theme.draw_text(
            self.screen,
            limit_text,
            (plans_card_rect.right - 20, plans_card_rect.bottom - 15),
            center=True,
            size=16,
            color=(100, 100, 100)
        )
        
        # 绘制第二条分隔线
        pygame.draw.line(
            self.screen, 
            self.theme.border_color,
            (50, 470),
            (self.width - 50, 470),
            2
        )
        
        # 绘制"选择学习方案"标题
        self.theme.draw_text(
            self.screen,
            "选择学习方案",
            (self.width/2, 500),
            center=True,
            size=24,
            color=self.theme.primary_color
        )
        
        # 获取推荐计划
        word_count = len(self.word_bank.words)
        recommendations = self.user_profile.get_plan_recommendations(word_count)
        
        # 绘制推荐方案卡片
        card_width = 200
        card_height = 150
        start_x = self.width/2 - (card_width * len(recommendations))/2 - (20 * (len(recommendations)-1))/2
        
        for i, plan in enumerate(recommendations):
            # 计算卡片位置
            card_x = start_x + i * (card_width + 20)
            card_y = 530
            
            card_rect = pygame.Rect(card_x, card_y, card_width, card_height)
            
            # 检测鼠标悬停
            mouse_pos = pygame.mouse.get_pos()
            is_hover = card_rect.collidepoint(mouse_pos)
            
            # 绘制卡片背景
            if is_hover:
                # 高亮显示
                self.theme.draw_card(self.screen, card_rect, with_shadow=True, border=2)
            else:
                self.theme.draw_card(self.screen, card_rect, with_shadow=True)
            
            # 绘制计划标题
            self.theme.draw_text(
                self.screen,
                plan["name"],
                (card_rect.centerx, card_rect.top + 30),
                center=True,
                size=22,
                color=self.theme.primary_color
            )
            
            # 绘制计划详情
            details = [
                f"每日: {plan['words_per_day']}词",
                f"用时: {plan['days']}天",
                f"目标: {plan['target_date']}"
            ]
            
            for j, detail in enumerate(details):
                self.theme.draw_text(
                    self.screen,
                    detail,
                    (card_rect.centerx, card_rect.top + 65 + j*25),
                    center=True,
                    size=16,
                    color=self.theme.text_color
                )
            
            # 保存按钮引用
            self.buttons[f"select_plan_{i}"] = card_rect
        
        # 绘制自定义计划按钮
        custom_plan_button = pygame.Rect(
            self.width/2 - 100, 
            self.height - 80, 
            200, 
            50
        )
        
        # 检测鼠标悬停
        is_custom_hover = custom_plan_button.collidepoint(mouse_pos)
        
        self.theme.draw_button(
            self.screen, 
            custom_plan_button, 
            "自定义计划", 
            is_hover=is_custom_hover
        )
        
        self.buttons["custom_plan"] = custom_plan_button
        
        # 如果有错误提示需要显示
        if getattr(self, 'show_error', False):
            current_time = pygame.time.get_ticks()
            # 显示3秒
            if current_time - self.error_show_time < 3000:
                # 创建半透明遮罩
                overlay = pygame.Surface((self.width, self.height))
                overlay.fill((0, 0, 0))
                overlay.set_alpha(128)
                self.screen.blit(overlay, (0, 0))
                
                # 绘制错误提示框
                error_width = 400
                error_height = 150
                error_rect = pygame.Rect(
                    self.width/2 - error_width/2,
                    self.height/2 - error_height/2,
                    error_width,
                    error_height
                )
                
                # 绘制背景
                self.theme.draw_card(self.screen, error_rect, with_shadow=True)
                
                # 绘制错误图标
                self.theme.draw_text(
                    self.screen,
                    "❌",
                    (error_rect.centerx, error_rect.top + 40),
                    center=True,
                    size=36,
                    color=self.theme.wrong_color
                )
                
                # 绘制错误信息
                self.theme.draw_text(
                    self.screen,
                    self.error_message,
                    (error_rect.centerx, error_rect.top + 90),
                    center=True,
                    size=24,
                    color=self.theme.wrong_color
                )
            else:
                # 3秒后清除错误状态
                self.show_error = False
    
    def _draw_wrapped_text(self, text: str, rect: pygame.Rect, size: int = 14, color = None) -> None:
        """绘制自动换行的文本
        
        Args:
            text: 要绘制的文本
            rect: 文本区域
            size: 字体大小
            color: 文本颜色
        """
        if not text:
            return
        
        x = rect.left
        y = rect.top
        
        # 对于中文文本，按字符分割
        chars = list(text)
        line = ""
        lines = []
        
        for char in chars:
            test_line = line + char
            test_width = self.theme.get_text_width(test_line, size=size)
            
            if test_width > rect.width:
                # 当前行已满，保存当前行并开始新行
                if line:
                    lines.append(line)
                line = char
            else:
                # 继续添加到当前行
                line = test_line
        
        # 添加最后一行
        if line:
            lines.append(line)
        
        # 限制最大行数
        max_lines = rect.height // (size + 4)  # 4是行间距
        if len(lines) > max_lines:
            # 如果超出最大行数，截断并添加省略号
            lines = lines[:max_lines-1]
            last_line = lines[-1]
            while self.theme.get_text_width(last_line + "...", size=size) > rect.width:
                last_line = last_line[:-1]
            lines[-1] = last_line + "..."
        
        # 绘制所有行
        for i, line in enumerate(lines):
            self.theme.draw_text(
                self.screen,
                line,
                (x, y + i * (size + 4)),  # 行间距为字体大小+4
                center=False,
                size=size,
                color=color
            )
    
    def _draw_study_interface(self) -> None:
        """绘制学习界面"""
        # 清理之前的按钮
        self.buttons.clear()
        
        if not self.today_words:
            # 绘制完成提示
            self.theme.draw_text(
                self.screen,
                "今日学习任务已完成！",
                (self.width/2, self.height/2 - 50),
                center=True,
                size=36
            )
            
            # 绘制返回按钮
            back_rect = pygame.Rect(self.width/2 - 100, self.height/2 + 50, 200, 40)
            pygame.draw.rect(self.screen, self.theme.border_color, back_rect, 1)
            self.theme.draw_text(
                self.screen,
                "返回菜单",
                (back_rect.centerx, back_rect.centery),
                center=True,
                size=24
            )
            self.buttons["back_to_menu"] = back_rect
            return
        
        # 绘制顶部信息栏
        info_bg = pygame.Rect(0, 0, self.width, 60)
        pygame.draw.rect(self.screen, (*self.theme.border_color[:3], 30), info_bg)
        
        # 绘制进度信息
        progress_text = f"今日进度: {self.current_word_index + 1}/{len(self.today_words)}"
        self.theme.draw_text(
            self.screen,
            progress_text,
            (20, 30),
            center=False,
            size=20
        )
        
        # 绘制计划名称
        if self.active_plan:
            plan_text = f"计划: {self.active_plan['name']}"
            self.theme.draw_text(
                self.screen,
                plan_text,
                (self.width - 20, 30),
                center=False,
                size=20,
                color=(100, 100, 100)
            )
        
        # 绘制统计信息
        if self.active_plan:
            stats_text = f"正确率: {self.user_profile.get_accuracy_rate()}% | 连续正确: {self.user_profile.get_current_streak()}"
            self.theme.draw_text(
                self.screen,
                stats_text,
                (self.width/2, 30),
                center=True,
                size=20,
                color=(100, 100, 100)
            )
        
        # 绘制单词区域
        word_bg = pygame.Rect(50, 100, self.width - 100, self.height - 200)
        pygame.draw.rect(self.screen, (*self.theme.border_color[:3], 10), word_bg)
        pygame.draw.rect(self.screen, self.theme.border_color, word_bg, 1)
        
        # 获取当前单词
        current_word = self.today_words[self.current_word_index]
        
        # 绘制单词
        self.theme.draw_text(
            self.screen,
            current_word["word"],
            (self.width/2, word_bg.top + 80),
            center=True,
            size=48
        )
        
        # 如果显示单词信息
        if self.show_word_info:
            # 获取词性和释义
            pos, meaning = self.word_bank.get_word_info(current_word["word"])
            
            # 绘制词性
            if pos:
                self.theme.draw_text(
                    self.screen,
                    pos,
                    (self.width/2, word_bg.top + 140),
                    center=True,
                    size=24,
                    color=(100, 100, 100)
                )
            
            # 绘制释义
            if meaning:
                self.theme.draw_text(
                    self.screen,
                    meaning,
                    (self.width/2, word_bg.top + 180),
                    center=True,
                    size=24
                )
        
        # 如果显示学习提示
        if not self.show_word_info:
            self.theme.draw_text(
                self.screen,
                "按空格键显示释义",
                (self.width/2, word_bg.top + 140),
                center=True,
                size=16,
                color=(160, 160, 160)
            )
        
        # 绘制输入框
        input_rect = pygame.Rect(
            self.width/2 - 200,
            word_bg.bottom - 120,
            400,
            50
        )
        # 自动激活输入框
        if not hasattr(self, 'input_active'):
            self.input_active = True
        pygame.draw.rect(self.screen, 
                        self.theme.highlight_color if self.input_active else self.theme.border_color, 
                        input_rect, 2)
        
        # 绘制输入的文本
        if self.current_input:
            self.theme.draw_text(
                self.screen,
                self.current_input,
                (input_rect.left + 10, input_rect.centery),
                center=False,
                size=24
            )
        else:
            # 显示提示文本
            self.theme.draw_text(
                self.screen,
                "输入单词后按回车",
                (input_rect.centerx, input_rect.centery),
                center=True,
                size=20,
                color=(160, 160, 160)
            )
        
        # 如果显示结果
        if self.show_result:
            result_color = self.theme.correct_color if self.result else self.theme.wrong_color
            result_text = "✅ 正确" if self.result else "❌ 错误"
            self.theme.draw_text(
                self.screen,
                result_text,
                (self.width/2, input_rect.bottom + 40),
                center=True,
                size=32,
                color=result_color
            )
            
            if not self.result:
                # 显示正确答案
                self.theme.draw_text(
                    self.screen,
                    f"正确答案: {self.today_words[self.current_word_index]['word']}",
                    (self.width/2, input_rect.bottom + 80),
                    center=True,
                    size=24,
                    color=self.theme.wrong_color
                )
        
        # 绘制底部操作提示
        hint_bg = pygame.Rect(0, self.height - 40, self.width, 40)
        pygame.draw.rect(self.screen, (*self.theme.border_color[:3], 30), hint_bg)
        
        hints = [
            "Enter: 确认",
            "Space: 显示/隐藏释义",
            "Tab: 朗读单词",
            "Esc: 返回菜单"
        ]
        
        hint_width = self.width / len(hints)
        for i, hint in enumerate(hints):
            self.theme.draw_text(
                self.screen,
                hint,
                (hint_width * i + hint_width/2, self.height - 25),
                center=True,
                size=16,
                color=(100, 100, 100)
            )
    
    def _draw_review_interface(self) -> None:
        """绘制复习界面"""
        # TODO: 实现复习界面的绘制
        pass

    def start_study(self):
        """开始学习"""
        words = self.game.get_practice_words(10)  # 获取10个新单词和需要复习的单词
        if not words:  # 如果没有获取到单词
            print("没有获取到学习单词")
            return
            
        self.study_started = True
        self.input_text = ""
        self.result = None
        self.show_result = False
        
        # 获取第一个单词
        self.game.get_next_word()
        
    def _handle_study_event(self, event: pygame.event.Event) -> str:
        """处理学习事件"""
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                return "menu"
                
            if not self.study_started:
                if event.key == pygame.K_RETURN:
                    self.start_study()
                return None
                
            if not self.game.current_word_info:  # 如果没有当前单词
                return None
                
            if self.show_result:
                if event.key == pygame.K_SPACE:
                    # 继续下一个单词
                    next_word = self.game.move_to_next_word()
                    if next_word:  # 如果有下一个单词
                        self.input_text = ""
                        self.result = None
                        self.show_result = False
                    else:  # 如果没有下一个单词
                        print("学习完成")
                return None
                
            if event.key == pygame.K_RETURN:
                # 检查输入
                self.result = self.game.check_input(self.input_text)
                if self.result:  # 如果检查结果有效
                    self.show_result = True
                    # 朗读当前单词
                    current_word = self.game.current_word_info.get("word")
                    if current_word:
                        self.speech.speak(current_word)
            elif event.key == pygame.K_BACKSPACE:
                self.input_text = self.input_text[:-1]
            else:
                # 只接受字母输入
                if event.unicode.isalpha() or event.unicode in ['-', ' ']:
                    self.input_text += event.unicode
                    
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # 左键点击
            mouse_pos = pygame.mouse.get_pos()
            
            # 未开始学习时的按钮
            if not self.study_started:
                if self.buttons["start"].collidepoint(mouse_pos):
                    self.start_study()
                    return None
                if self.buttons["menu"].collidepoint(mouse_pos):
                    return "menu"
                    
            # 已开始学习时的按钮
            elif self.game.current_word_info:
                if self.show_result:
                    if self.buttons["next"].collidepoint(mouse_pos):
                        # 继续下一个单词
                        next_word = self.game.move_to_next_word()
                        if next_word:
                            self.input_text = ""
                            self.result = None
                            self.show_result = False
                        else:
                            print("学习完成")
                else:
                    if self.buttons["check"].collidepoint(mouse_pos):
                        # 检查输入
                        self.result = self.game.check_input(self.input_text)
                        if self.result:
                            self.show_result = True
                            current_word = self.game.current_word_info.get("word")
                            if current_word:
                                self.speech.speak(current_word)
        
        return None
        
    def _handle_plan_selection_event(self, event: pygame.event.Event) -> str:
        """处理计划选择事件"""
        # TODO: 实现计划选择事件的处理逻辑
        return None
    
    def _handle_create_plan_event(self, event: pygame.event.Event) -> str:
        """处理创建计划事件"""
        # TODO: 实现创建计划事件的处理逻辑
        return None
        
    def _handle_study_event(self, event: pygame.event.Event) -> str:
        """处理学习事件"""
        # TODO: 实现学习事件的处理逻辑
        return None
        
    def _handle_plan_selection_event(self, event: pygame.event.Event) -> str:
        """处理计划选择事件"""
        # TODO: 实现计划选择事件的处理逻辑
        return None
        
    def _handle_create_plan_event(self, event: pygame.event.Event) -> str:
        """处理创建计划事件"""
        # TODO: 实现创建计划事件的处理逻辑
        return None
        
    def _create_plan_from_template(self, plan: Dict) -> None:
        """从模板创建学习计划"""
        try:
            success = self.user_profile.create_study_plan(
                plan["name"],
                self.word_bank.current_bank,
                plan["words_per_day"],
                plan["target_date"]
            )
            
            if success:
                self.active_plan = self.user_profile.get_active_plan()
                self.state = "study"
                self.load_study_words()
            else:
                # 添加错误提示状态
                self.show_error = True
                self.error_message = "已达到最大学习计划数量限制"
                self.error_show_time = pygame.time.get_ticks()  # 记录错误显示开始时间
        except Exception as e:
            # 处理其他可能的错误
            self.show_error = True
            self.error_message = str(e)
            self.error_show_time = pygame.time.get_ticks()

    def _show_create_plan_dialog(self) -> None:
        """显示自定义计划对话框"""
        # 切换到自定义计划状态
        self.state = "custom_plan"
        
        # 初始化自定义计划的参数
        if not hasattr(self, 'custom_plan_params'):
            self.custom_plan_params = {
                'name': '自定义计划',
                'words_per_day': 20,
                'duration_days': 60,
                'active_field': None  # 当前激活的输入字段
            }
        
        # 刷新按钮
        self.refresh_buttons()

    def _draw_custom_plan_dialog(self) -> None:
        """绘制自定义计划对话框"""
        # 创建半透明遮罩
        overlay = pygame.Surface((self.width, self.height))
        overlay.fill((0, 0, 0))
        overlay.set_alpha(128)
        self.screen.blit(overlay, (0, 0))
        
        # 对话框尺寸和位置
        dialog_width = 500
        dialog_height = 300
        dialog_x = self.width/2 - dialog_width/2
        dialog_y = self.height/2 - dialog_height/2
        
        # 绘制对话框背景
        dialog_rect = pygame.Rect(dialog_x, dialog_y, dialog_width, dialog_height)
        pygame.draw.rect(self.screen, self.theme.background_color, dialog_rect)
        pygame.draw.rect(self.screen, self.theme.border_color, dialog_rect, 2)
        
        # 绘制标题
        self.theme.draw_text(
            self.screen,
            "自定义学习计划",
            (self.width/2, dialog_y + 30),
            center=True,
            size=24
        )
        
        # 绘制输入字段
        fields = [
            ('计划名称', 'name', str),
            ('每日单词数', 'words_per_day', int),
            ('学习天数', 'duration_days', int)
        ]
        
        for i, (label, key, _) in enumerate(fields):
            y_pos = dialog_y + 80 + i * 60
            
            # 绘制标签
            self.theme.draw_text(
                self.screen,
                label,
                (dialog_x + 40, y_pos + 20),
                center=False,
                size=16
            )
            
            # 绘制输入框
            input_rect = pygame.Rect(dialog_x + 200, y_pos, 250, 40)
            if self.custom_plan_params['active_field'] == key:
                pygame.draw.rect(self.screen, self.theme.highlight_color, input_rect, 2)
            else:
                pygame.draw.rect(self.screen, self.theme.border_color, input_rect, 1)
            
            # 绘制当前值
            self.theme.draw_text(
                self.screen,
                str(self.custom_plan_params[key]),
                (input_rect.left + 10, input_rect.centery),
                center=False,
                size=16
            )
            
            # 保存输入框位置
            self.buttons[f"input_{key}"] = input_rect
        
        # 绘制按钮
        button_y = dialog_y + dialog_height - 60
        
        # 确认按钮
        confirm_rect = pygame.Rect(dialog_x + 100, button_y, 140, 40)
        pygame.draw.rect(self.screen, self.theme.highlight_color, confirm_rect)
        self.theme.draw_text(
            self.screen,
            "确认",
            (confirm_rect.centerx, confirm_rect.centery),
            center=True,
            size=20,
            color=self.theme.background_color
        )
        self.buttons["custom_confirm"] = confirm_rect
        
        # 取消按钮
        cancel_rect = pygame.Rect(dialog_x + 260, button_y, 140, 40)
        pygame.draw.rect(self.screen, self.theme.border_color, cancel_rect, 1)
        self.theme.draw_text(
            self.screen,
            "取消",
            (cancel_rect.centerx, cancel_rect.centery),
            center=True,
            size=20
        )
        self.buttons["custom_cancel"] = cancel_rect 